# !/bin/sh

# rmemptydir.sh
# removes all empty subdirectories in a directory, recursively. 
# The directory name is a parameter of the script.

# written by Sean Yang, yang.xin.00@gmail.com, Apr. 19, 2007

# usage
function usage(){
    echo "usage:";
    echo "       rmemptydir dir";
}

function prompt_not_exist {
    echo "$1 doesn't exist!";
}

function prompt_not_directory {
    echo "$1 isn't a directory!";
}

# parameter check
if [ -z $1 ]; then
  usage;
  exit 0;
fi

# $1 exist?
if [ ! -e $1 ]; then
  prompt_not_exist $1;
  exit 0;
# $1 is a directory?
else if [ ! -d $1 ]; then
  prompt_not_directory $1;
  exit 0;
fi
fi

# my first try.
# remove empty subdirectories recursively.
# first, try to remove all subdirectories if possible;
# then, try to remove myself.
#function rmdir_r {
#    # check made upon the first invoke
#    if [ -z $1 ]; then
#        echo "No parameter passed to rmdir_r!";
#        return 0;
#    fi
#
#    if [ ! -e $1 ]; then
#        prompt_not_exist $1;
#        return 0;
#    fi
#
#    # base case, leaf node in file tree.
#    # if not a directory, then a file, just return and do nothing
#    if [ ! -d $1 ]; then
#        return 0;
#    fi
#
#    # a directory
#    # invoke rmdir_r recursively on $1's subdirectories 
#    for item in $(ls $1); do
#          rmdir_r $1/$item;
#    done
#
#    # subdirectories done, then try to rmdir myself
#    rmdir --ignore-fail-on-non-empty $1;
#}

# my second try based on the following reference
function rmdir_r {
# until the bottomest "directory"
# a regular file will never be the parameter of rmdir_r due to -d
    for item in $1/*
    do
      if test -d $item
      then 
        rmdir_r $item
      fi
    done

# count the number of subdirectory and file
    n=0
    for item in $1/*
    do
# the directories except the bottomest ones also need this count 
# after return from their subdirectories
      if test -d $item
      then
        ((n=n+1))
      fi
# the bottomest directory only need this count
      if test -f $item
      then
        ((n=n+1))
      fi
    done

# echo "$1 counts $n"
    if [ $n -eq 0 ] 
    then
      rmdir $1
    fi
}

echo "before rmdir_r:"
echo "+++++++++++++++++++"
tree $1
rmdir_r $1
echo "+++++++++++++++++++"
echo "after rmdir_r:"
tree $1

# reference: http://www.moon-soft.com/doc/49494.htm
# check-and-do from the bottomest level of file tree.
#
# for name in  $1/*
# do
# if test -d $name
# then
# sh delete.csh $name
# fi
# done
# 
# var=0
# for x in $1/*
# do
# if test -d $x
# then 
# var=`expr $var + 1`
# fi
# if test -f $x
# then
# var=`expr $var + 1`
# fi
# done
# if [ $var -eq 0 ]
# then
# rmdir $1
# fi


